/*
 * COPYRIGHT. ShenZhen JiMi Technology Co., Ltd. 2017.
 * ALL RIGHTS RESERVED.
 *
 * No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
 * on any form or by any means, electronic, mechanical, photocopying, recording, 
 * or otherwise, without the prior written permission of ShenZhen JiMi Network Technology Co., Ltd.
 *
 * Amendment History:
 * 
 * Date                   By              Description
 * -------------------    -----------     -------------------------------------------
 * 2017年4月10日    li.shangzhi         Create the class
 * http://www.jimilab.com/
 */

package com.jimi;

import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import springfox.documentation.swagger2.annotations.EnableSwagger2;

import com.jimi.framework.context.SpringContextHolder;
import com.jimi.framework.filter.ApiOriginFilter;
import com.jimi.framework.oval.MyGuardInterceptor;
import com.jimi.tracker.client.RouteClientPool;

/**
 * @FileName ClientApiApplication.java
 * @Description: api-server启动入口
 *
 * @Date 2017年4月10日 下午3:03:01
 * @author li.shangzhi
 * @version 1.0
 */
@EnableTransactionManagement
@SpringBootApplication
@EnableSwagger2
@ComponentScan(basePackages = "com.jimi")
//@ImportResource({ "classpath:applicationContext-dubbo.xml"})
public class JimiClientApiApplication implements CommandLineRunner {

	private static final Logger logger = LoggerFactory.getLogger(JimiClientApiApplication.class);

	private static final String EXIT_CODE = "exitcode";
	
	@Value("${tracker.sendDictate.url}")
	private String sendDictateUrl;

	@Value("${tracker.sendDictate.port}")
	private String sendDictatePort;
	
	@Value("${language}")
	private String language;

	@Override
	public void run(String... args) throws Exception {
		if (args.length > 0 && EXIT_CODE.equals(args[0])) {
			throw new ExitException();
		}
		logger.info("初始化RouteClientPool，ip：{}，port：{}", sendDictateUrl, sendDictatePort);
		try {
			RouteClientPool.init(sendDictateUrl, Integer.valueOf(sendDictatePort));
		} catch (NullPointerException e) {
			// 这里有坑，RouteClientPool里面会静态初始加载一个conf.properties文件，这里不会有这个文件
		}
		
		if("zh".equals(language)) {
			// 设置默认语言环境  
	        Locale.setDefault(Locale.CHINA);
		} else {
			// 设置英文语言环境  
	        Locale.setDefault(Locale.US);
		}
	}

	public static void main(String[] args) {
		new SpringApplication(JimiClientApiApplication.class).run(args);
		logger.info("====================Jimi Client Api Server启动成功!====================");
	}
	
	@Bean
	public ApiOriginFilter apiOriginFilter() {
		return new ApiOriginFilter();
	}
	
	@Bean(name = "ovalGuardInterceptor")
	public MyGuardInterceptor ovalGuardInterceptor() {
		MyGuardInterceptor myGuardInterceptor = new MyGuardInterceptor();
		return myGuardInterceptor;
	}
	
	@Bean()
	public BeanNameAutoProxyCreator adapter() {
		BeanNameAutoProxyCreator adapter = new BeanNameAutoProxyCreator();
		adapter.setProxyTargetClass(true);
		adapter.setBeanNames("*ApiController*");
		adapter.setInterceptorNames("ovalGuardInterceptor");
		return adapter;
	}

	@Bean
	public MessageSource messageSource() {
		final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
		messageSource.setBasename("i18n/messages");
		messageSource.setFallbackToSystemLocale(false);
		messageSource.setCacheSeconds(0);
		messageSource.setDefaultEncoding("UTF-8");
		return messageSource;
	}

	@Bean
	public SpringContextHolder springContextHolder() {
		return new SpringContextHolder();
	}

	class ExitException extends RuntimeException implements ExitCodeGenerator {
		private static final long serialVersionUID = 1L;

		@Override
		public int getExitCode() {
			return 10;
		}
	}

}
